﻿module Sustainalytics.Authentication {

    export var authenticationHttpInterceptorName = 'AuthenticationHttpInterceptor';


    var factory = function (

        $rootScope: RootScope,
        $q: ng.IQService,
        $location: ng.ILocaleService,
        staticObjects: Common.IStaticObjects) {

        return {
            request: (config: ng.IRequestConfig) => {

                config.headers = config.headers || {};

                //If we want to use the Angular generation of exago reports.
                //if ($rootScope.authData && $rootScope.authData.access_token && config.url.indexOf("rest/sessions") == -1 && config.url.indexOf("rest/parameters") == -1) {
                if ($rootScope.authData && $rootScope.authData.access_token) {
                    config.headers.Authorization = 'Bearer ' + $rootScope.authData.access_token;
                }

                return config;
            },

            response: (response) => {
                return response || $q.when(response);
            }
        }
    };


    angular.module(authenticationModuleName).factory(authenticationHttpInterceptorName, ['$rootScope', '$q', '$location', 'staticObjects', factory]);
} 